package k3.net.local
{
	import flash.events.DatagramSocketDataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.DatagramSocket;
	import flash.utils.ByteArray;
	import flash.utils.setTimeout;
	public class BoardUDPCaster extends EventDispatcher
	{
		private var datagramSocket:DatagramSocket = new DatagramSocket();
		private var ip:String;
		private var port:uint;
		private var targetPort:uint;
		private var ipduans:Vector.<String>;
		private var level0:int=0;
		private var level1:int=0;
		private var targetStr:String;
		/**
		 * 
		 * @param _ip			本地ip
		 * @param _port			本地端口
		 * @param _targetPort	目标端口
		 * @param _targetStr	广播内容
		 * 
		 */
		public function BoardUDPCaster(_ip:String,_port:uint,_targetPort:uint,_targetStr:String) 
		{
			ip=_ip;
			port=_port;
			targetPort=_targetPort;
			targetStr=_targetStr;
			bind();
		}
		
		private function bind():void
		{
			try
			{
				datagramSocket.bind(port, ip );
			}
			catch(e:Error)
			{
				trace(e.message);
				
				setTimeout(bind,3000);
				return;
			}
			
			boardCast();
			
			
		}
		
		/**
		 * 
		 * @param str 192.168.1. 或 192.168.2.
		 * 
		 */
		public function addIpDuan(str:String):void
		{
			if(!ipduans)
			{
				ipduans=new Vector.<String>();
			}
			
			ipduans.push(str);
		}
		
		private function boardCast():void
		{
			if(!ipduans)
			{
				setTimeout(boardCast,1000);
				return;
			}
			if(ipduans.length==0)
			{
				setTimeout(boardCast,1000);
				return;
			}
			if(level0<255)
			{
				//不需要0
				level0++;
			
				var targetIp:String=ipduans[level1]+level0.toString();
				sendMessage(targetIp);
				setTimeout(boardCast,20);
			}
			else
			{
				level1++;
				if(level1>ipduans.length-1)
				{
					level1=0;
					level0=0;
				}
				boardCast();
			}
		}
		
		
		private function sendMessage(targetIp:String):void
		{
			var data:ByteArray = new ByteArray();
			data.writeUTFBytes( targetStr );
			try
			{
				datagramSocket.send(data, 0, 0,targetIp,targetPort); 
			}
			catch(e:Error)
			{
				trace(e.message);
				
				return;
			}
		}
		
	}
}